package cn.hls.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import cn.hls.dao.CompanyDao;
import cn.hls.entity.CertSet;
import cn.hls.entity.Company;
import cn.hls.entity.vo.PageInfo;
import cn.hls.exception.BussinessException;
import cn.hls.until.GenericsUtils;
import cn.hlsconstant.CommonEnum;
import cn.hlsconstant.DataAssessEnum;

 
/**
 *@fileName: CompanyDaoImpl.java
 *@package: cn.christ.dao.impl
 *@Description:  会友数据接口实现类
 *@author: yinghui.zhang
 *@email: uuhui@163.com
 *@date: 2015-7-18
 */
@Component("companyDao")
public class CompanyDaoImpl extends BaseDaoImpl<Company> implements CompanyDao {
	@Override
	public PageInfo<Company> loadCompanyInfo(Company entity, PageInfo<Company> page) throws Exception {
		// 定义查询Hql语句
		StringBuilder selectHql=new StringBuilder("from Company p where p.deleted=? ");
		// 定义汇总Hql语句
		StringBuilder counthql = new StringBuilder("select count(p.id) ");
		// 定义查询参数
		List<Object> paramList = new ArrayList<Object>();
		paramList.add(false);
		if (entity != null) {
			//按全称名称查询
			 if(StringUtils.hasText(entity.getName())){
				 selectHql.append("and name like ? ");
				 paramList.add("%"+entity.getName().trim()+"%");
			 }
			 
			 if(StringUtils.hasText(entity.getBussinessRegisteNum())){
				 selectHql.append("and bussinessRegisteNum like ? " );
				 paramList.add("%"+entity.getBussinessRegisteNum().trim()+"%");
			 }
			 //按企业类型查询
			 if(entity.getType()!=null){
				 selectHql.append("and p.type=? ");
				 paramList.add(entity.getType());
			 }
			
			 //类型为承运企业按编号查询
			 if(entity.getType()!=null && entity.getType().intValue()==1&& entity.getId()!=null){
				 selectHql.append("and id=? ");
				 paramList.add(entity.getId());
			 }else{
				 //按承运企业编号查询
				 if(entity.getCarryCompanyId()!=null){
					 selectHql.append("and carryCompanyId=? ");
					 paramList.add(entity.getCarryCompanyId());
				 }
			 }
			 if(StringUtils.hasText(entity.getSearchAttribute())){
				 selectHql.append("and p."+entity.getSearchAttribute()+"Num is not null ");
				 selectHql.append("and (p."+entity.getSearchAttribute()+"Validity is null ");
				 selectHql.append("or p."+entity.getSearchAttribute()+"Validity<=sysdate )");
			 }
		}
		counthql. append(selectHql);
		selectHql.append(" order by p.createTime");
		return find(selectHql.toString(), counthql.toString(), paramList.toArray(), page);
	}
	
	@Override
	public List<Company> loadCompanyList(Company entity)throws Exception{
		// 定义查询Hql语句
		StringBuilder selectHql=new StringBuilder("from Company p where p.deleted=? ");
		// 定义查询参数
		List<Object> paramList = new ArrayList<Object>();
		paramList.add(false);
		if (entity != null) {
			//按企业编号查询
			if(entity.getId()!=null){
				selectHql.append("and p.id=? ");
				paramList.add(entity.getId());
			}
			//按全称名称查询
			 if(StringUtils.hasText(entity.getName())){
				 selectHql.append("and name like ? ");
				 paramList.add("%"+entity.getName().trim()+"%");
			 }
			//按企业类型查询
			 if(entity.getType()!=null){
				 selectHql.append("and p.type=? ");
				 paramList.add(entity.getType());
				 //按承运企业编号查询
				 if(entity.getCarryCompanyId()!=null){
					if(entity.getType().intValue()==2){
						selectHql.append("and p.carryCompanyId=? ");
					}else{
						selectHql.append("and id=? ");//按企业编号进行过滤
					}
					paramList.add(entity.getCarryCompanyId());
				 }
			 }else{//未设置企业类型，则根据查询企业编号及承运方的企业信息
				 if(entity.getCarryCompanyId()!=null){
						selectHql.append("and p.carryCompanyId=? or id=? ");
						paramList.add(entity.getCarryCompanyId());
						paramList.add(entity.getCarryCompanyId());
					 }
			 }
			
		}
		return findByHql(selectHql.toString(), paramList.toArray());
	}

	@Override
	public void delete(Object entityId) throws Exception {
		String []ids=(String[])entityId;
		StringBuilder hql=new StringBuilder("update Company set deleted=? where id in (");
		List<Object>params=new ArrayList<Object>();
		params.add(true);
		for (String id:ids){
			hql.append("?,");
			params.add(Long.valueOf(id));
		}	
		hql.delete(hql.length()-1, hql.length());
		hql.append(")");
		 try {
			executeHQLUpdate(hql.toString(), params.toArray());
		} catch (Exception e) {
			e.printStackTrace();
			throw new BussinessException(DataAssessEnum.UPDATE_ERROR,"删除企业信息失败" );
		}
	}

	
	@Override
		public boolean exists(Company entity)throws Exception{
			StringBuilder selectHql=new StringBuilder("select count(id) from Company where deleted=? ");
			List<Object>params=new ArrayList<Object>();
			params.add(false);
			if(entity!=null){
				
				if(entity.getName()!=null){//企业全称　
					selectHql.append("and (name=? ");
					params.add(entity.getName());
				}
				if(StringUtils.hasText(entity.getBussinessRegisteNum())){//工商注册号查询
					selectHql.append("or bussinessRegisteNum=?) ");
					params.add(entity.getBussinessRegisteNum().trim());
				}else{
					selectHql.append(")");
				}
			}
			Query query=this.getSession().createQuery(selectHql.toString());
			for(int i=0;i<params.size();i++){
				query.setParameter(i, params.get(i));
			}
			Long c = Long.valueOf(((Number) query.uniqueResult()).longValue());
			return c.intValue()>0?true:false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Company> loadCompanyOfShipper(Company entity) throws Exception {
		StringBuilder hql=new StringBuilder("select new cn.hls.entity.Company( p.id,c.name) ");
		hql.append("from Shipper p inner join  p.company c where p.deleted=? ");
		List<Object>params=new ArrayList<>();
		params.add(false);
		if(entity!=null){
			//根据编号查询
			if(entity.getId()!=null){
				hql.append("and c.id=? ");
				params.add(entity.getId());
			}
			//根据名称查询
			if(StringUtils.hasText(entity.getName())){
				hql.append("and c.name like ? ");
				params.add("%"+entity.getName().trim()+"%");
			}
			//根据承运企业编号查询
			if(entity.getCarryCompanyId()!=null){
				hql.append("and c.carryCompanyId=? ");
				params.add(entity.getCarryCompanyId());
			}
		}
		Query query =getSession().createQuery(hql.toString());
		for(int i=0;i<params.size();i++){
			query.setParameter(i, params.get(i));
		}
		return query.list();
	}

	@Override
	public Map<String, Integer> loadExpiredCompany(Long companyId,Map<String, CertSet> cetSetMap) throws Exception {
		Map<String,Integer>map=new HashMap<String, Integer>();
		String hql=null;
		if(companyId==null){
			//工商注册号有效期过期汇总
			hql="select count(p.id) from Company p where p.deleted=? and type=? and bussinessRegisteNum is not null and (bussinessRegisteValidity is null or bussinessRegisteValidity<=?) ";
			map.put("bussinessRegiste", countByHql(hql,new Object[]{false,1,GenericsUtils.getPreMonthTime(new Date(),cetSetMap.get("bussinessRegiste")==null?1:cetSetMap.get("bussinessRegiste").getPreMonth().intValue())}).intValue());
			//经营许可证有效期过期汇总
		    hql="select count(p.id) from Company p where p.deleted=? and type=? and bussinessLicenseNum is not null and (bussinessLicenseValidity is null or bussinessLicenseValidity<=?) ";
			map.put("bussinessLicense", countByHql(hql,new Object[]{false,1,GenericsUtils.getPreMonthTime(new Date(),cetSetMap.get("bussinessLicense")==null?1:cetSetMap.get("bussinessLicense").getPreMonth().intValue())}).intValue());
		}else{
			//工商注册号有效期过期汇总
			hql="select count(p.id) from Company p where p.deleted=? and id=? and type=? and bussinessRegisteNum is not null and (bussinessRegisteValidity is null or bussinessRegisteValidity<=?) ";
			map.put("bussinessRegiste", countByHql(hql,new Object[]{false,companyId,1,GenericsUtils.getPreMonthTime(new Date(),cetSetMap.get("bussinessRegiste")==null?1:cetSetMap.get("bussinessRegiste").getPreMonth().intValue())}).intValue());
			//经营许可证有效期过期汇总
		    hql="select count(p.id) from Company p where p.deleted=? and id=? and type=? and bussinessLicenseNum is not null and (bussinessLicenseValidity is null or bussinessLicenseValidity<=?) ";
			map.put("bussinessLicense", countByHql(hql,new Object[]{false,companyId,1,GenericsUtils.getPreMonthTime(new Date(),cetSetMap.get("bussinessLicense")==null?1:cetSetMap.get("bussinessLicense").getPreMonth().intValue())}).intValue());
		}
		return map;
	}

	@Override
	public List<Company> loadExpiredCompanyList(Company entity,
			Map<String, CertSet> cetSetMap) throws Exception {
		StringBuilder hql=new StringBuilder("from Company p where p.deleted=? and type=? and (");
		List<Object>params=new ArrayList<Object>();
		params.add(false);
		params.add(Integer.parseInt(CommonEnum.CARRYCOMPANY.getCode()));
		hql.append("(p.bussinessRegisteNum is not null and (p.bussinessRegisteValidity is null or p.bussinessRegisteValidity<=?)) or ");
		params.add(GenericsUtils.getPreMonthTime(new Date(),cetSetMap.get("bussinessRegiste")==null?1:cetSetMap.get("bussinessRegiste").getPreMonth().intValue()));
		hql.append("( p.bussinessLicenseNum is not null and (p.bussinessLicenseValidity is null or p.bussinessLicenseValidity<=?))");
		params.add(GenericsUtils.getPreMonthTime(new Date(),cetSetMap.get("bussinessLicense")==null?1:cetSetMap.get("bussinessLicense").getPreMonth().intValue()));
		hql.append(")");
		return findByHql(hql.toString(), params.toArray());
	}

}
